package com.karry.yl.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.Constants;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.AESUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.Menu;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.baseinfo.PaymentInfo;
import com.karry.yl.domain.system.Resources;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.baseinfo.PaymentInfoService;
import com.karry.yl.service.system.LoginService;
import com.karry.yl.web.interceptor.CookieKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author tianxuan
 * @version V1.0
 * @Date 2017/10/16 0016 上午 10:44
 * @Description: 登录/退出控制器
 */
@Controller
@RequestMapping
public class LoginController extends SuperController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private OrganizationService organizationService;

    @RequestMapping("/login")
    public String loginUI() {
        return "login";
    }

    /**
     * @return
     */
    @RequestMapping("/login/verify")
    @ResponseBody
    public JsonResponse verify(String accountNumber, String password, String captcha, Integer automatic, HttpServletRequest request, HttpServletResponse response) throws SQLException {

        int code = JsonResponse.CODE_SUCCESS;
        String msg = "登陆成功";
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Date date = (Date) session.getAttribute(Constants.KAPTCHA_SESSION_DATE);
        if (null == sessionCode || null == captcha || !sessionCode.equals(captcha) || ((System.currentTimeMillis() - date.getTime()) / 1000 / 60 > 15)) {
            code = JsonResponse.CODE_FAIL;
            msg = "验证码错误或失效";
        } else {
            User user = loginService.login(accountNumber, password);
            if (null != user && user.getStatus() == 1) {
                session.setAttribute(Constants.SK_USER, user);    //登陆成功则将用户信息存入session
                Organization organization = organizationService.selectById(user.getOrgId());
                session.setAttribute(Constants.SK_JG, organization);    //登陆成功则将机构信息存入session

                List<Menu> menus = loginService.menus(user.getRoleId());
                session.setAttribute(Constants.SK_MENUS, menus); //将主页菜单存进session
                List<Resources> topMenus = loginService.topMenus(user.getRoleId());
                session.setAttribute(Constants.SK_TOP_MENUS, topMenus); //将主页顶部快速导航菜单存进session
                Map<String, Resources> resourcesMap = loginService.myResources(user.getRoleId());
                session.setAttribute(Constants.SK_ALL_RESOURCES, resourcesMap); //将该用户所有权限存进session
                Map<String, List<String>> pageSubResCode = loginService.myPageResources(user.getRoleId());
                session.setAttribute(Constants.SK_PAGE_SUB_RES_CODE, pageSubResCode); //将该用户每个页面拥有的操作权限code存进session
                //如果用户勾选了自动登陆，token存进cookie
                if (automatic != null && automatic == 1) {
                    //勾选了自动登陆功能,就向cookie添加账户密码
                    //设置cookie的存货时间,存活时间为30天
                    Cookie cookie = new Cookie(CookieKey.HUHIJHHIUAUSDGUIASHDJASU.toString(), AESUtil.encrypt(accountNumber,CookieKey.AGSHIDGDIUAG.toString()));
                    Cookie cookie2 = new Cookie(CookieKey.SIOJHSOIOISJAIODOIAJSDO.toString(),  AESUtil.encrypt(password,CookieKey.AGSHIDGDIUAG.toString()));
                    //设置保存时间
                    cookie.setMaxAge(30 * 24 * 60 * 60);
                    cookie2.setMaxAge(30 * 24 * 60 * 60);
                    //设置保存路径
                    cookie.setPath(request.getContextPath() + "/");
                    cookie2.setPath(request.getContextPath() + "/");
                    //添加到响应头
                    response.addCookie(cookie);
                    response.addCookie(cookie2);

                }
            } else {
                code = JsonResponse.CODE_FAIL;
                msg = "用户名或密码错误";
            }
        }
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        session.removeAttribute(Constants.KAPTCHA_SESSION_DATE);
        return new JsonResponse(code, msg);
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session,HttpServletResponse response) {
        session.removeAttribute(Constants.SK_USER);
        session.removeAttribute(Constants.SK_JG);
        session.removeAttribute(Constants.SK_MENUS);
        session.removeAttribute(Constants.SK_TOP_MENUS);
        session.removeAttribute(Constants.SK_ALL_RESOURCES);
        session.removeAttribute(Constants.SK_PAGE_SUB_RES_CODE);
        Cookie cookie = new Cookie(CookieKey.HUHIJHHIUAUSDGUIASHDJASU.toString(), null);
        Cookie cookie2 = new Cookie(CookieKey.SIOJHSOIOISJAIODOIAJSDO.toString(), null);
        //设置保存时间
        cookie.setMaxAge(0);
        cookie2.setMaxAge(0);
        //添加到响应头
        response.addCookie(cookie);
        response.addCookie(cookie2);
        return "redirect:/login";
    }
}
